<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------


namespace app\admin\controller;
use \think\Cookie;
use app\admin\model\Theme as ThemeModel;
use app\admin\model\Goods as G;
use think\Db;
class Theme extends User
{

    public function index()
    {
        $model = new ThemeModel();
        $post = $this->request->post();
        //分页bug处理
        $temp_page=request()->param('page');
        if(isset($temp_page)){
            //条件从缓存取出
            $post=Cookie::get('postlisttheme');
        }else{
            //把条件写入缓存
            Cookie::set('postlisttheme',$post);
        }
        $where=[];
        if (isset($post['keywords']) and !empty($post['keywords'])) {
            $where['name'] = ['like', '%' . $post['keywords'] . '%'];
        }

        if (isset($post['status']) and $post['status'] > 0) {
            $where['status'] = $post['status'];
        }

        $info=$model->where($where)->order('sortNum desc')->paginate(20);

        foreach ($info as $k=>$v) {
            //获取tag
            $tag=$v['tag_id'];
            $tag=explode(',',$tag);
            if($tag[0]){
                $tagdata=Array();
                foreach($tag as $key=>$value){
                    $tags=db('tag')->where("tag_id",$value)->field("tag_name,tag_id")->find();
                    $tagdata[$key]=$tags;
                }
            }else{
                $tagdata='';
            }
            $info[$k]['tagdata'] = $tagdata;
        }

        $this->assign('info', $info);
        $this->assign('wherelist', $post);
        return $this->fetch();
    }


    //新建主题
    public function addtheme()
    {
        $model = new ThemeModel();
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;

        $tag= model('Tag')->where('tag_type','2')->where('tag_status','NEQ','2')->select();
        $this->assign('tag', $tag);

        if ($id > 0) {
            //是修改操作
            if ($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['name', 'require', '主题名称不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }

                $basetagname = db("theme")->where('id', $id)->field('name')->find();

                if($basetagname['name']!=$post['name']){
                    //验证名称是否存在
                    $where['name']=$post['name'];
                    $nickname = db("theme")->where($where)->select();
                    if (!empty($nickname)) {
                        return $this->error('提交失败：该主题名称已被存在');
                    }
                }

                $post['updatetime']=time();

                if (false == $model->allowField(true)->save($post, ['id' => $id])) {
                    return $this->error('修改失败');
                } else {
                    return $this->success('修改主题成功', 'admin/theme/index');
                }
            } else {
                //非提交操作
                $info = $model->where('id', $id)->find();

                //获取tag
                $tag=$info['tag_id'];
                $tag=explode(',',$tag);
                if($tag[0]){
                    $tagdata=Array();
                    foreach($tag as $key=>$value){
                        $tags=db('tag')->where("tag_id",$value)->field("tag_name,tag_id")->find();
                        $tagdata[$key]=$tags;
                    }
                }else{
                    $tagdata='';
                }
                $this->assign('tagdata',$tagdata);

                $this->assign('info', $info);
                return $this->fetch();
            }
        } else {
            //是新增操作
            if ($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();

                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['name', 'require', '主题名称不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }

                $where['name']=$post['name'];
                //验证名称是否存在
                $themename = db("theme")->where($where)->select();
                if (!empty($themename)) {
                    return $this->error('提交失败：该主题名称已存在');
                }

                $post['creattime']=time();
                $post['updatetime']=time();

                if (false == $model->allowField(true)->save($post)) {
                    return $this->error('添加主题失败');
                } else {
                    return $this->success('添加主题成功', 'admin/theme/index');
                }
            } else {
                //非提交操作
                return $this->fetch();
            }
        }
    }


    //启用&禁用主题
    public function delete()
    {
        if($this->request->isAjax()) {
            $model = new ThemeModel();
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            $status = $this->request->has('status') ? $this->request->param('status', 0, 'intval') : 0;
            if($status){
                $data['status'] =$status;
            }
            if($status==2){
                $msg='禁用';
            }else{
                $msg='启用';
            }
            $data['updatetime']=time();
            if (false == $model->allowField(true)->save($data, ['id' => $id])) {
                return $this->error($msg.'失败');
            } else {
                return $this->success($msg.'主题成功', 'admin/theme/index');
            }
        }
    }
    //主题商品列表权重
    public function themeprolist()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;

        if(!isset($id) || empty($id)){
            $this->error("参数有误");
        }
        $themeinfo = db("theme")->find($id);
        if(empty($themeinfo)){
            $this->error("theme信息不存在");exit;
        }elseif(empty($themeinfo['tag_id'])){
            $this->error("该theme下暂无标签");exit;
        }else{
            $tag_ids = explode(",",$themeinfo['tag_id']);
            if(empty($tag_ids)){
                $this->error("该theme下暂无标签");exit;
            }
        }
        $post = request()->post();
        //分页bug处理
        $temp_page=request()->param('page');
        if(!empty($temp_page)){
            $where = cache("themepro_where");
        }else{
            $where = [];
            if(isset($post['goods_id']) && !empty($post['goods_id'])){
                $where['g.goods_id'] = $post['goods_id'];
            }
            if(isset($post['goods_name']) && !empty($post['goods_name'])){
                $where['g.goods_name'] = ["like",'%'.$post['goods_name'].'%'];
            }
            cache("themepro_where",$where);
        }
//        var_dump($temp_page,$where);exit;
        $search_page = 15;
        //首先查询所有goods_id,进行结果集排序,分页
        $field = "c.name as city_name,g.goods_id,goods_name,goods_englishname,g.city_id,price_section,goods_image,goods_introduce";
        $model = (new ThemeModel())->getThemeSortGoods($themeinfo,$field,$where);
        $prolist = $model->paginate($search_page);
        foreach ($prolist as $key=>$value){
            $images = array_filter(explode(",",$value['goods_image']));
            $prolist[$key]['goods_image'] = empty($images)?"":array_shift($images);
        }
        $this->assign('info', $prolist);
        $this->assign('wherelist', $post);
        $this->assign('sort', explode(",",$themeinfo['sort']));
        $this->assign('theme', $themeinfo);
        return $this->fetch();
    }


    //对商品进行排序
    public function sortThemeGoods()
    {
        $post = request()->post();
        $themeid = isset($post['theme_id'])&&!empty($post['theme_id'])?$post['theme_id']:0;
        $theme = db("theme")->find($themeid);
        if(empty($theme)){
            return json(['code'=>-1,'msg'=>'主题信息有误']);
        }

        $goods_id = isset($post['goods_id'])&&!empty($post['goods_id'])?$post['goods_id']:0;
        $goods = db("goods")->find($goods_id);
        if(empty($goods)){
            return json(['code'=>-1,'msg'=>'商品信息有误']);
        }
        //主题排序
        if(empty($theme['sort'])){
            $res = db("theme")->where("id",$themeid)->update(['sort'=>$goods_id]);
        }else{
            $sort = explode(",",$theme['sort']);
            $index = array_search($goods_id,$sort);
            if($index!==false){
                unset($sort[$index]);
            }
            array_unshift($sort,$goods_id);
            $sort_str = implode(",",$sort);
            $res = db("theme")->where("id",$themeid)->update(['sort'=>$sort_str]);
        }

        if($res!==false){
            return json(['code'=>200,'msg'=>'置顶成功']);
        }else{
            return json(['code'=>-1,'msg'=>'置顶失败']);
        }
    }

    //清空排序
    public function emptySort()
    {
        $post = request()->post();
        $themeid = isset($post['theme_id'])&&!empty($post['theme_id'])?$post['theme_id']:0;
        $theme = db("theme")->find($themeid);
        if(empty($theme)){
            return json(['code'=>-1,'msg'=>'主题信息有误']);
        }
        if(empty($theme['sort'])){
            return json(['code'=>-1,'msg'=>'主题商品排序已清空']);
        }
        $res = db("theme")->where("id",$themeid)->update(['sort'=>'']);
        if($res!==false){
            return json(['code'=>200,'msg'=>'主题商品排序清空成功']);
        }else{
            return json(['code'=>-1,'msg'=>'主题商品排序清空成功']);
        }
    }
}
